﻿#include <thread>
#include "ui_server.h"
#include "../../log_tool.h"
#include "ui_msg_handle.h"

#include <windows.h>
#include "ui_msg/ui_msg_def.h"


WubiUIServer::WubiUIServer(std::shared_ptr<WubiSchemeMgr> &wubi_scheme_mgr)
    : _wubi_scheme_mgr(wubi_scheme_mgr),
    _has_client(false),
    IpcServerBase(UI_PIPE_SIZE, UI_PIPE_NAME){
        _uiMsgHandler = std::make_shared<UIMsgHandler>();
}
WubiUIServer::~WubiUIServer(){

}

void WubiUIServer::onClientConnected(HANDLE hPipe){
    char *buffer = new char[UI_PIPE_SIZE];
    DWORD bytesRead;

    // 只允许一个客户端连接
    if(_has_client){
        delete[] buffer;
        LOG_INFO("已有客户端连接");
        DisconnectNamedPipe(hPipe);
        CloseHandle(hPipe);
        return;
    }

    _has_client = true;
    while (true)
    {
        // 读取客户端消息
        if (!ReadFile(hPipe, buffer, UI_PIPE_SIZE, &bytesRead, NULL))
        {
            if (GetLastError() == ERROR_BROKEN_PIPE)
            {
                LOG_INFO("客户端断开连接");
            }
            else
            {
                LOG_ERROR("读取数据失败: %d", GetLastError());
            }
            break;
        }
        //处理数据
        if(!_uiMsgHandler->handleMsg(hPipe,_wubi_scheme_mgr,buffer,bytesRead)){
            LOG_ERROR("处理取数据失败");
            break;
        }
    }

    // 清理资源
    delete[] buffer;
    // Flush the pipe to allow the client to read the pipe's contents 
    // before disconnecting. Then disconnect the pipe, and close the 
    // handle to this pipe instance. 
    FlushFileBuffers(hPipe); 
    DisconnectNamedPipe(hPipe);
    CloseHandle(hPipe);

    _has_client = false;
}

bool WubiUIServer::start(){
    return IpcServerBase::start([this](HANDLE hPipe){
        std::thread clientThread(
            &WubiUIServer::onClientConnected,
            this,
            hPipe
        );
        clientThread.detach();
    });
}